<template>
  <a-upload

      name="avatar"
      listType="picture-card"
      class="avatar-uploader"
      :show-Upload-List="false"
      :customRequest="upload"
      :before-upload="beforeUpload"
      @change="handleChange"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="img"/>
    <div v-else>
      <loading-outlined v-if="loading"></loading-outlined>
      <plus-outlined v-else></plus-outlined>
      <div class="ant-upload-text">头像</div>
    </div>
  </a-upload>
</template>

<script setup>
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { onMounted, ref} from "vue";
import request from "@/utils/request";
import {put} from "@/utils/OSS";


const loading = ref(false);
// const url=ref('')
const imageUrl = ref()

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
onMounted(()=>{
  request.get('admin/get/avatar').then(res=>{
    console.log(res)
    imageUrl.value=res.data
  })
})

const handleChange = info => {
  if (info.file.status === 'uploading') {
    loading.value = true;
    return;
  }

  if (info.file.status === 'done') {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, base64Url => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
  }

  if (info.file.status === 'error') {
    loading.value = false;
    message.error('upload error');
  }
};

const beforeUpload = file => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

  if (!isJpgOrPng) {
    message.error('You can only upload JPG file!');
  }

  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }

  return isJpgOrPng && isLt2M;
};

function upload(action) {
  const file = action.file
  put("avatar/avatar", file).then(result => {
    loading.value = false
    imageUrl.value = result.url
    console.log(imageUrl.value)
    request.post("admin/update/avatar",result.url).then(res=>console.log(res))
    // store.commit("setImageUrl", this.imageUrl)

  }).catch(e => {
    // this.log('异常')
    put("avatar/avatar", file).then(result => {
      loading.value = false
      imageUrl.value = result.url
      // store.commit("setImageUrl", this.imageUrl)
    })
  })
}

</script>

<style scoped>
.img {
  width: 128px;
  height: 128px;
  object-fit: cover;
  object-position: 50% 20%;
}

.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;

}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>